<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/12/19
 * Time: 9:13
 * @content 员工提成--门店结算
 */

namespace app\service;


use Redis\Redis;
use think\Db;

class CommissionService
{
    /**
     * @param int $bizId 门店id
     * @param int $workOrderId 工单id
     * @param int $workOrderType 工单类型 1=>服务   2商品
     * @param int $carLevel 车辆等级  1->小型车  2->中型车  3->大型车
     * @param string $operation 操作标识  1->添加   2->评论修改
     * @param int $employee_id 员工id
     * @param int $comm 评论得分  0->不满意  3->一般  5 满意
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 计算提成
     */
    function commission($bizId, $workOrderId, $workOrderType, $carLevel, $operation = 'add', $employee_id = 0, $comm = 3)
    {
        # 当前时间
        $time = date('Y-m-d H:i:s');
        # 判断门店类型,自定义商品/服务/推荐提成比例
        $redis = new Redis();
        $bizCommissionInfo = CommissionService::getBizCommissionInfo($bizId);
        # 查询工单详情
        $workOrderDetail = $redis->hGetJson('workOrderDetail', $workOrderId . '_' . $workOrderType);
        if (empty($workOrderDetail)) {
            if ($workOrderType == 1) {
                # 服务工单 =>  order_server
                $workOrderDetail = Db::table('order_server')
                    ->field('order_number,server_id pid,price,employee_id,custommark,referrer,coupon_mark,station_id,original_price,price_settlement')
                    ->where(array('id' => $workOrderId))
                    ->find();
            } else {
                # 商品工单==>  order_biz
                $workOrderDetail = Db::table('order_biz')
                    ->field('order_number,biz_pro_id pid,pro_price price,employee_id,referrer,custommark,coupon_mark,station_id,original_pro_price original_price,
                price_settlement')
                    ->where(array('id' => $workOrderId))
                    ->find();
            }
            $redis->hSetJson('workOrderDetail', $workOrderId . '_' . $workOrderType, $workOrderDetail, strtotime(date('Y-m-d 23:59:59')) - time());
        }
        if (empty($workOrderDetail)) {
            return array('status' => false, 'msg' => '未查到对应工单信息');
        }
        # 查询工位对应的提成比例
        if ($workOrderDetail['station_id']) {
            # 选择了工位
            $stationCommissionInfo = $redis->hGetJson('stationCommission', $workOrderDetail['station_id']);
            if (empty($stationCommissionInfo)) {
                $stationCommissionInfo = Db::table('station')
                    ->field('negative_price,timer,service_deduct,biz_deduct,recommond_royalty,recommond_custom_pro,recommond_custom_service,
                custom_pro_deduct,custom_service_deduct,recommond_pro_royalty')
                    ->where(array('id' => $workOrderDetail['station_id']))
                    ->find();
                $redis->hSetJson('stationCommission', $workOrderDetail['station_id'], $stationCommissionInfo);
            }
        } else {
            # 没选择工位
            $stationCommissionInfo = array();
        }
        # 结算价格
        $settlement_price = CommissionService::settlementPrice($workOrderDetail['pid'], $workOrderType,
            $workOrderDetail['price'], $workOrderDetail['custommark'], $carLevel, $bizId);
        # 开始计算提成
        $deductArr = array();
        if ($workOrderType == 1) {
            # 查询最低提成标准
            $serviceMin = $redis->hGet('serviceMin', $workOrderDetail['pid']);
            if (empty($serviceMin)) {
                $serviceMin = Db::table('service')->field('service_minprice')
                    ->where(array('id' => $workOrderDetail['pid']))
                    ->value('service_minprice');
                $redis->hSet('serviceMin', $workOrderDetail['pid'], $serviceMin);
            }
            if ($settlement_price < $serviceMin) {
                $settlement_price = $serviceMin;
            }
        }
        # 服务提成
        if (!empty($workOrderDetail['employee_id'])) {
            $employeeArr = explode(',', $workOrderDetail['employee_id']);
            # 服务人员计算提成
            $ratio = CommissionService::deductRatio($stationCommissionInfo, $bizCommissionInfo, $workOrderDetail['pid'], $workOrderType, $workOrderDetail['custommark'], 1);
            $deduct = $settlement_price * $ratio;
            # 添加超时扣款
            $deduction = 0;
            if ($workOrderType == 1 && $operation == 'add') {
                # 查询是否存在扣款
                $timeout = Db::table("log_order_timeout")->where(array(
                    "order_number" => $workOrderDetail['order_number'],
                    "order_server_id" => $workOrderId,
                    "iscut" => 1
                ))->find();
                if (!empty($timeout)) {
                    # 查询该服务每分钟扣款多少钱
                    $overtime_price = Db::table('service_class sc')
                        ->field('sc.service_outtime')
                        ->where("sc.id = (select s.service_class_id from service s where s.id=" . $workOrderDetail['pid'] . ")")
                        ->value('service_outtime');
                    if ($overtime_price != 0) {
                        # 计算工单超时时间
                        $overtime_diff = floor((strtotime($timeout['order_over']) - strtotime($timeout['order_endtime'])) % 86400 / 60);
                        $deduction = -($overtime_price * $overtime_diff);
                    }
                }
            }
            if ($operation == 'add') {
                # 添加
                $deduct = $deduct * config('ratios.comment_rate_commission')['medium'] / count($employeeArr);
            } else {
                # 评论修改提成
                if ($comm == 5) {
                    # 好评
                    $deduct = $deduct * config('ratios.comment_rate_commission')['good'] / count($employeeArr);
                } elseif ($comm == 3 or $comm == 4) {
                    # 中评
                    $deduct = $deduct * config('ratios.comment_rate_commission')['medium'] / count($employeeArr);
                } else {
                    # 差评
                    $deduct = $deduct * config('ratios.comment_rate_commission')['bad'] / count($employeeArr);
                }
            }
            if ($operation == 'add') {
                foreach ($employeeArr as $k => $v) {
                    # 添加提成
                    # 提成
                    array_push($deductArr, array(
                        'order_number' => $workOrderDetail['order_number'],
                        'order_server_id' => $workOrderId,
                        'type' => $workOrderType == 1 ? 2 : 1,
                        'employee_id' => $v,
                        'deduct' => $deduct,
                        'create' => $time,
                        'refer_mark' => 1,
                        'exec_update' => 1,
                        'biz_id' => $bizId
                    ));
                    # 超时扣款(只有直营店有超时扣款)
                    if ($deduction > 0 and $bizCommissionInfo['biz_type'] == 1) {
                        array_push($deductArr, array(
                            'order_number' => $workOrderDetail['order_number'],
                            'order_server_id' => $workOrderId,
                            'type' => $workOrderType == 1 ? 2 : 1,
                            'employee_id' => $v,
                            'deduct' => $deduction,
                            'create' => $time,
                            'refer_mark' => 1,
                            'exec_update' => 1,
                            'biz_id' => $bizId
                        ));
                    }
                }
            } else {
                # 修改提成
                Db::table('deduct')->where(array(
                    'order_number' => $workOrderDetail['order_number'],
                    'order_server_id' => $workOrderId,
                    'type' => $workOrderType == 1 ? 2 : 1,
                    'employee_id' => $employee_id,
                    'refer_mark' => 1,
                    'exec_update' => 1,
                    'biz_id' => $bizId
                ))
                    ->update(array('deduct' => $deduct));
                if ($comm == 0 and $bizCommissionInfo['biz_type'] == 3) {
                    # 合作店差评额外扣款 , 直营店 在 算薪资的时候计算的差评
                    $badPrice = $bizCommissionInfo['negative_price'] ? $bizCommissionInfo['negative_price'] : config('ratios.comment_bad');
                    # 添加数据
                    if ($badPrice > 0) {
                        array_push($deductArr, array(
                            'order_number' => $workOrderDetail['order_number'],
                            'order_server_id' => $workOrderId,
                            'type' => $workOrderType == 1 ? 2 : 1,
                            'employee_id' => $employee_id,
                            'deduct' => -$badPrice,
                            'create' => $time,
                            'refer_mark' => 1,
                            'exec_update' => 2,
                            'biz_id' => $bizId
                        ));
                    }
                }
            }
        }
        # 推荐提成
        if (!empty($workOrderDetail['referrer'])) {
            $referrerArr = explode(',', $workOrderDetail['referrer']);
            # 推荐人员计算提成
            $ratio = CommissionService::deductRatio($stationCommissionInfo, $bizCommissionInfo,$workOrderDetail['pid'], $workOrderType, $workOrderDetail['custommark'], 2);
            $deduct = $settlement_price * $ratio;
            if ($bizCommissionInfo['biz_type'] == 1) {
                # 直营店  推荐  走评论
                if ($operation == 'add') {
                    # 添加
                    $deduct = $deduct * config('ratios.comment_rate_commission')['medium'] / count($referrerArr);
                } else {
                    # 评论修改提成
                    if ($comm == 5) {
                        # 好评
                        $deduct = $deduct * config('ratios.comment_rate_commission')['good'] / count($referrerArr);
                    } elseif ($comm == 3 or $comm == 4) {
                        # 中评
                        $deduct = $deduct * config('ratios.comment_rate_commission')['medium'] / count($referrerArr);
                    } else {
                        # 差评
                        $deduct = $deduct * config('ratios.comment_rate_commission')['bad'] / count($referrerArr);
                    }
                }
            } else {
                # 合作店--推荐提成和 评论没关系
                $deduct = $deduct / count($referrerArr);
            }
            if ($operation == 'add') {
                # 添加
                foreach ($referrerArr as $k => $v) {
                    array_push($deductArr, array(
                        'order_number' => $workOrderDetail['order_number'],
                        'order_server_id' => $workOrderId,
                        'type' => $workOrderType == 1 ? 2 : 1,
                        'employee_id' => $v,
                        'deduct' => $deduct,
                        'create' => $time,
                        'refer_mark' => 2,
                        'exec_update' => 1,
                        'biz_id' => $bizId
                    ));
                }
            } else {
                # 评论修改提成
                if ($bizCommissionInfo['biz_type'] == 1) {
                    # 直营店 根据评论 修改推荐提成
                    # 修改提成
                    Db::table('deduct')->where(array(
                        'order_number' => $workOrderDetail['order_number'],
                        'order_server_id' => $workOrderId,
                        'type' => $workOrderType == 1 ? 2 : 1,
                        'employee_id' => $employee_id,
                        'exec_update' => 1,
                        'refer_mark' => 2,
                        'biz_id' => $bizId
                    ))
                        ->update(array('deduct' => $deduct));
                }
            }
        }

        if (!empty($deductArr)) {
            Db::table('deduct')->insertAll($deductArr);
        }
    }

    /**
     * @param $orderNumber
     * @param $payType
     * @param $orderPrice
     * @param $couponPrice
     * @param $bizId
     * @param string $mark
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 合作门店订单结算(添加数据/评论修改数据)
     */
    function bizSettlement($orderNumber, $payType, $orderPrice, $couponPrice, $bizId, $mark = 'add')
    {
        # 计算该订单的结算价格
        $bizCommissionInfo = CommissionService::getBizCommissionInfo($bizId);
        if ($bizCommissionInfo['biz_type'] == 1) {
            return array('status' => false, 'msg' => '直营店没有结算');
        }
        # 查询订单详情
        # 商品工单
        $orderBiz = Db::table('order_biz ob')
            ->field('ob.pro_price,ob.original_pro_price original_price,price_settlement,final_settlement,2 type,custommark,
            (select score from evaluation_score where orderserver_id = ob.id and type=2 limit 1) score')
            ->where(array('order_number' => $orderNumber))
            ->buildSql();
        # 查询该订单下的服务工单
        $temporary = Db::table('order_server os')
            ->field('os.price,os.original_price,price_settlement,final_settlement,1 type,custommark,
            (select score from evaluation_score where orderserver_id = os.id and type=1 limit 1) score')
            ->where(array('order_number' => $orderNumber))
            ->union([$orderBiz])
            ->buildSql();
        # 联合查询
        $orderDetail = Db::table($temporary . 't')->select();
        if (!empty($orderDetail)) {
            $price = 0;
            $withdrawal_amount = 0;
            $withdrawal_amount_count = 0;
            $finishTask = true;
            foreach ($orderDetail as $k => $v) {
                if ($v['score'] == 0) {
                    $finishTask = false;
                    $settlement_ratio = config('ratios.comment_rate_settlement')['bad'];
                } elseif ($v['score'] == 3 or $v['score'] == 4 or is_null($v['score'])) {
                    $finishTask = false;
                    $settlement_ratio = config('ratios.comment_rate_settlement')['medium'];
                } else {
                    $settlement_ratio = config('ratios.comment_rate_settlement')['good'];
                }
                if ($v['type'] == 1) {
                    # 服务工单
                    # 计算抽成
                    if ($v['custommark'] == 1) {
                        # 系统服务
                        $withdrawal_amount += $v['price_settlement'] * $bizCommissionInfo['extract_platservice'];
                        $withdrawal_amount_count += $v['price_settlement'] * $bizCommissionInfo['extract_platservice'] * $settlement_ratio;
                    } else {
                        # 自定义服务
                        $withdrawal_amount += $v['price_settlement'] * $bizCommissionInfo['extract_selfservice'];
                        $withdrawal_amount_count += $v['price_settlement'] * $bizCommissionInfo['extract_selfservice'] * $settlement_ratio;
                    }
                    $settlement_order = $v['price_settlement'] - $withdrawal_amount;
                    # 结算金额
                    $price += ($settlement_order * $settlement_ratio);
                } else {
                    # 商品工单
                    # 计算抽成
                    if ($v['custommark'] == 1) {
                        # 系统服务
                        $withdrawal_amount += $v['price_settlement'] * $bizCommissionInfo['extract_platpro'];
                        $withdrawal_amount_count += $v['price_settlement'] * $bizCommissionInfo['extract_platpro'] * $settlement_ratio;
                    } else {
                        # 自定义服务
                        $withdrawal_amount += $v['price_settlement'] * $bizCommissionInfo['extract_selfpro'];
                        $withdrawal_amount_count += $v['price_settlement'] * $bizCommissionInfo['extract_selfpro'] * $settlement_ratio;
                    }
                    $settlement_order = $v['price_settlement'] - $withdrawal_amount;
                    # 结算金额
                    $price += ($settlement_order * $settlement_ratio);
                }
            }
            # 判断结算方式
            if ($payType == 3 or $payType == 4) {
                # 银联/现金  给我们钱啊
                $price = $price - ($orderPrice - $couponPrice);
            }
            if ($mark == 'add') {
                # 添加结算
                Db::table('biz_settlement')->insert(array(
                    'order_number' => $orderNumber,
                    'price' => $price,
                    'tobe_settled' => $price + $withdrawal_amount_count,
                    'type' => 1,
                    'method' => $payType,
                    'create_time' => date('Y-m-d H:i:s'),
                    'order_price' => $orderPrice,
                    'coupon_price' => $couponPrice,
                    'commission_price' => $withdrawal_amount_count,
                    'biz_id' => $bizId
                ));
            } else {
                $settlement_status = 2;
                $desposit_status = 2;
                if ($bizCommissionInfo['security_price'] == 0) {
                    # 直接加余额
                    Db::table('biz')->where(array('id' => $bizId))->setInc('account_balance', $price);
                } else {
                    $settlement_status = 1;

                    # 判断是否超过押金
                    if ($price + $bizCommissionInfo['settlement_count'] > $bizCommissionInfo['security_price']) {
                        $settlement_status = 2;
                        #加余额
                        Db::table('biz')->where(array('id' => $bizId))->setInc('account_balance', ($price + $bizCommissionInfo['settlement_count'] - $bizCommissionInfo['security_price']));
                        Db::table('biz')->where(array('id' => $bizId))->update('settlement_count', $bizCommissionInfo['security_price']);
                    }else{
                        Db::table('biz')->where(array('id' => $bizId))->setInc('settlement_count', $price);
                    }
                }
                Db::table('biz_settlement')
                    ->where(array(
                        'order_number' => $orderNumber,
                        'type' => 1,
                        'method' => $payType,
                        'biz_id' => $bizId
                    ))->update(array(
                        'price' => $price,
                        'tobe_settled' => $price + $withdrawal_amount_count,
                        'commission_price' => $withdrawal_amount_count,
                        "settlement_status" => $settlement_status,
                        "desposit_status" => $desposit_status
                    ));
                $redis = new Redis();
                $redis->hDel('bizCommission', $bizId);
                # 完成任务--销售额
                CommissionService::FinishCooperativeTask(2, $bizId, $price);
                if ($finishTask) {
                    CommissionService:: FinishCooperativeTask(4, $bizId, 1);
                }
            }
        }
    }

    /**
     * @param int $assignBizId
     * @param $employeeId
     * @param string $mark
     * @param $price
     * @param $memberId
     * @param int $level_id
     * @param int $up_level
     * @param string $orderNumber
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content  办理会员/会员充值/会员升级---加员工提成 / 合作门店 加提成 , 计算结算金额
     */
    function cooperativeDeduct($assignBizId = 1, $employeeId, $mark = 'Membership', $price, $memberId, $level_id = 0, $up_level = 0, $orderNumber = '')
    {
        $deduct = 0;
        if ($mark == 'Membership') {
            # 办理会员
            $cooperBiz = 0.06;//提成比例
            $deductType = 3;//提成类型
            $settlementType = 2;//结算类型
            $orderNumber = $level_id;//订单编号
        } else {
            # 升级/充值
            $cooperBiz = 0.02;
            if ($mark == 'upgrade') {
                # 升级
                $deductType = 4;
                $settlementType = 3;
                $orderNumber = $level_id . ',' . $up_level;
            } else {
                # 充值
                $deductType = 5;
                $settlementType = 4;
            }
        }
        # 查询是否有绑定的员工和门店
        if (!empty($employeeId) or !empty($assignBizId)) {
            $bindingInfo = array();
            if (!empty($employeeId)) {
                $bindingInfo['employee_id'] = $employeeId;
            }
            if (!empty($assignBizId)) {
                $bindingInfo['biz_id'] = $assignBizId;
            } else {
                if(!empty($employeeId)) {
                    $bindingInfo['biz_id'] = Db::table('employee')->field('biz_id')->where(array('id' => $employeeId))->value('biz_id');
                }else{
                    $bindingInfo['biz_id'] = 0;
                }
            }
        } else {
            $bindingInfo = Db::table('log_handlecard')
                ->field("0 employee_id,biz_id")
                ->where(array('member_id' => $memberId))
                ->order(array('id' => 'desc'))->find();
        }
        if (!empty($bindingInfo)) {
            if (!empty($bindingInfo['employee_id'])) {
                # 员工提成
                $deduct = getsPriceFormat(floatval(floatval($price) * $cooperBiz / 2));
                Db::table("deduct")->insert(
                    array(
                        "order_number" => $level_id,
                        'order_server_id' => $memberId,
                        'type' => $deductType,
                        'employee_id' => $employeeId,
                        'deduct' => $deduct,
                        'refer_mark' => 3,
                        'biz_id' => $bindingInfo['biz_id'],
                        'create' => date("Y-m-d H:i:s")
                    )
                );
                # 查询是否是指派员工
                $isAssign = Db::table('assign_staff')->field('id')
                    ->where(array('biz_id' => $bindingInfo['biz_id'], 'employee_id' => $employeeId, 'type' => 1))->find();
                if (!empty($isAssign)) {
                    # 指派员工
                    $cooperBiz = $cooperBiz / 2;
                }
            }else{
                # 没有员工,只有门店
                $cooperBiz = $cooperBiz / 2;
            }
            # 增加合作门店/加盟门店结算金额
            $bizInfo = CommissionService::getBizCommissionInfo($bindingInfo['biz_id']);
            if (!empty($bizInfo) and $bizInfo['biz_type'] != 1) {
                $end_settlement = getsPriceFormat(floatval(floatval($price) * $cooperBiz));
                $commission_price = 0;
                # 加结算
                Db::table("biz_settlement")->insert(
                    array("price" => $end_settlement, "commission_price" => $commission_price,
                        "desposit_status" => 1, 'order_price' => $price,
                        'biz_id' => $bindingInfo['biz_id'], 'order_number' => $orderNumber,
                        'create_time' => date('Y-m-d H:i:s'), 'tobe_settled' => $end_settlement,
                        'method' => 1, 'type' => $settlementType, "settlement_status" => 1,
                        'member_id' => $memberId)
                );
                # 门店加提成
                Db::table("deduct")->insert(
                    array(
                        "order_number" => $orderNumber,
                        'order_server_id' => $memberId,
                        'type' => $deductType,
                        'employee_id' => 0,
                        'deduct' => $end_settlement,
                        'refer_mark' => 3,
                        'biz_id' => $bindingInfo['biz_id'],
                        'create' => date("Y-m-d H:i:s")
                    )
                );
                # 完成任务
                if ($mark == 'Membership') {
                    # 办理会员金额/办理会员数量
                    CommissionService::FinishCooperativeTask(1, $bindingInfo['biz_id'], 1);
                    CommissionService::FinishCooperativeTask(5, $bindingInfo['biz_id'], $price);
                }
            }
        }
        return array("employee_deduct" => $deduct);
    }

    /**
     * @param $task_type
     * @param $biz_id
     * @param $complete_num
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @content 合作端完成任务
     */
    static function FinishCooperativeTask($task_type, $biz_id, $complete_num)
    {
        if (empty($task_type) or empty($biz_id)) {
            return array('status' => false, 'msg' => '参数存在空值');
        }
        # 查询该门店是否存在该类型的正在进行中的任务
        $taskInfo = Db::query("select tl.id,task_num,complete_num from cooperative_task_list tl 
left join cooperative_task t on t.id=tl.task_id 
where biz_id = " . $biz_id . " and status = 1 and type = " . $task_type);
        if (empty($taskInfo)) {
            return array('status' => false, 'msg' => '没有可完成任务');
        }
        if ($complete_num < 0) {
            $complete_num = -$complete_num;
        }
        # 判断状态
        $complete = $taskInfo[0]['complete_num'] + $complete_num;
        if ($taskInfo[0]['task_num'] <= $complete) {
            $arr = array('status' => 2, 'complete_num' => $complete, 'completion_time' => date('Y-m-d H:i:s'));
        } else {
            $arr = array('complete_num' => $complete);
        }
        Db::table('cooperative_task_list')->where(array('id' => $taskInfo[0]['id']))->update($arr);
        return array('status' => true, 'msg' => '距离完成任务又近了一步');
    }

    /**
     * @param $bizId
     * @return array|bool|mixed|null|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 获取门店信息
     */
    static function getBizCommissionInfo($bizId)
    {
        $redis = new Redis();
        $bizCommissionInfo = $redis->hGetJson('bizCommission', $bizId);
        if (empty($bizCommissionInfo)) {
            //->field('biz_type,account_balance,security_price,settlement_count,proportion,extract_selfservice,extract_selfpro')
            $bizCommissionInfo = Db::table('biz')
                ->where(array('id' => $bizId))
                ->find();
            $redis->hSetJson('bizCommission', $bizId, $bizCommissionInfo);
        }
        return $bizCommissionInfo;
    }

    /*  static function settlementPrice($orderNumber)
      {
          # 查询订单详情
          # 商品工单
          $orderBiz = Db::table('order_biz ob')
              ->field('ob.pro_price,ob.original_pro_price,')
              ->where(array('order_number' => $orderNumber))
              ->buildSql();
          # 查询该订单下的服务工单
          $temporary = Db::table('order_server os')
              ->field('os.price,os.original_price ')
              ->where(array('order_number' => $orderNumber))
              ->union([$orderBiz])
              ->buildSql();
          # 联合查询
          $orderDetail = Db::table($temporary . 't')->select();
      }*/

    /**
     * @param array $stationCommissionInfo 工位提成信息
     * @param array $bizCommissionInfo 门店信息
     * @param int $serviceId 服务id/商品id
     * @param int $type 类型 1->服务  2->商品
     * @param int $custom 是否自定义  1->系统  2->自定义
     * @param int $mark 标识  1->服务提成   2->推荐提成
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 提成比例
     */
    static protected function deductRatio($stationCommissionInfo, $bizCommissionInfo, $serviceId, $type, $custom, $mark)
    {
        # 需要判断门店类型 , 直营店使用工位设置的 , 合作店使用门店里面设置的+
        switch ($type . $custom . $mark) {
            case '111':
            default:
                # 系统服务提成
                if ($bizCommissionInfo['biz_type'] == 1) {
                    # 直营店
                    $deduct = $stationCommissionInfo['service_deduct'] ?? 0;
                } else {
                    # 合作店
                    $deduct = $bizCommissionInfo['commission_platservice'] ?? 0;
                }
                if (empty($deduct)) {
                    $deduct = CommissionService::getDeductRatio($serviceId, 1);
                }
                break;
            case '112':
                # 系统服务推荐提成
                if ($bizCommissionInfo['biz_type'] == 1) {
                    # 直营店
                    $deduct = $stationCommissionInfo['recommond_royalty'] ?? 0;
                } else {
                    # 合作店
                    $deduct = $bizCommissionInfo['recommond_commission_platservice'] ?? 0;
                }
                if (empty($deduct)) {
                    $deduct = CommissionService::getDeductRatio($serviceId, 2);
                }
                break;
            case '121':
                # 自定义服务提成
                if ($bizCommissionInfo['biz_type'] == 1) {
                    # 直营店
                    $deduct = $stationCommissionInfo['custom_service_deduct'] ? $stationCommissionInfo['custom_service_deduct'] : config('ratios.custom_service_rate');
                } else {
                    # 合作店
                    $deduct = $bizCommissionInfo['commission_selfservice'] ? $bizCommissionInfo['commission_selfservice'] : config('ratios,custom_service_rate');
                }
                break;
            case '122':
                # 自定义服务推荐提成
                if ($bizCommissionInfo['biz_type'] == 1) {
                    # 直营店
                    $deduct = $stationCommissionInfo['recommond_custom_service'] ? $stationCommissionInfo['recommond_custom_service'] : config('ratios.custom_service_rate');
                } else {
                    # 合作店
                    $deduct = $bizCommissionInfo['recommond_commission_selfservice'] ? $bizCommissionInfo['recommond_commission_selfservice'] : config('ratios,custom_service_rate');
                }
                break;
            case '211':
                # 系统商品提成
                if ($bizCommissionInfo['biz_type'] == 1) {
                    # 直营店
                    $deduct = $stationCommissionInfo['biz_deduct'] ? $stationCommissionInfo['biz_deduct'] : config('ratios.pro_rate');
                } else {
                    # 合作店
                    $deduct = $bizCommissionInfo['commission_platpro'] ? $bizCommissionInfo['commission_platpro'] : config('ratios.pro_rate');
                }
                break;
            case '212':
                # 系统商品推荐提成
                if ($bizCommissionInfo['biz_type'] == 1) {
                    # 直营店
                    $deduct = $stationCommissionInfo['recommond_pro_royalty'] ? $stationCommissionInfo['recommond_pro_royalty'] : config('ratios.pro_rate');
                } else {
                    # 合作店
                    $deduct = $bizCommissionInfo['recommond_commission_platpro'] ? $bizCommissionInfo['recommond_commission_platpro'] : config('ratios.pro_rate');
                }
                break;
            case '221':
                # 自定义商品提成
                if ($bizCommissionInfo['biz_type'] == 1) {
                    # 直营店
                    $deduct = $stationCommissionInfo['custom_pro_deduct'] ? $stationCommissionInfo['custom_pro_deduct'] : config('ratios.pro_rate');
                } else {
                    # 合作店
                    $deduct = $bizCommissionInfo['commission_selfpro'] ? $bizCommissionInfo['commission_selfpro'] : config('ratios.pro_rate');
                }
                break;
            case '222':
                # 自定义商品推荐提成
                if ($bizCommissionInfo['biz_type'] == 1) {
                    # 直营店
                    $deduct = $stationCommissionInfo['recommond_custom_pro'] ? $stationCommissionInfo['recommond_custom_pro'] : config('ratios.pro_rate');
                } else {
                    # 合作店
                    $deduct = $bizCommissionInfo['recommond_commission_selfpro'] ? $bizCommissionInfo['recommond_commission_selfpro'] : config('ratios.pro_rate');
                }
                break;
        }
        return $deduct;
    }

    /**
     * @param $pid
     * @param $mark
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 获取服务提成比例信息
     */
    static function getDeductRatio($pid, $mark)
    {
        # 系统服务
        $redis = new Redis();
        $info = $redis->hGetJson('serviceRatio', $pid);
        if (empty($info)) {
            $info = Db::table('service')->field('service_refer,service_minprice,service_commission')
                ->where(array('id' => $pid))
                ->find();
            $redis->hSetJson('serviceRatio', $pid, $info);
        }
        switch ($mark) {
            case 1:
            default:
                # 系统服务提成
                $deduct = $info['service_commission'] ? $info['service_commission'] : config('ratios.service_rate');
                break;
            case 2:
                # 系统服务推荐提成
                $deduct = $info['service_refer'] ? $info['service_commission'] : config('ratios.service_rate');
                break;
        }
        return $deduct;
    }

    static protected function settlementPrice($serviceId, $type, $price, $custom, $carLevel, $bizId)
    {
        if ($custom == 1) {
            # 系统
            if ($type == 1) {
                # 系统服务
                $settlement_price = Db::table('service_car_mediscount')
                    ->field('settlement_amount')
                    ->where(array('service_id' => $serviceId, 'car_level_id' => $carLevel, 'service_type' => 1, 'biz_id' => $bizId))
                    ->value('settlement_amount');
                if(empty($settlement_price)){
                    $settlement_price = $price;
                }
            } else {
                # 自定义服务
                $settlement_price = $price;
            }
        } else {
            # 自定义
            if ($type == 1) {
                # 系统商品
                $settlement_price = $price;
            } else {
                # 自定义商品
                $settlement_price = $price;
            }
        }
        return $settlement_price;
    }
}
